package app.messages.repository;

import app.messages.model.Message;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class MessageRepository {
    private final static Log logger = LogFactory.getLog(MessageRepository.class);

    private SessionFactory sessionFactory;

    public MessageRepository(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Message saveMessage(Message message) {
        // Save message to a database
        logger.info("Saved message: " + message.getText());

        //open session从datasource获取
        //Session session = sessionFactory.openSession();

        //从当前hibernate context获取 其呗transaction advisor共享
        Session session = sessionFactory.getCurrentSession();
        session.save(message);
        return message;

    }

    public List<Message> getMessages() {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Message";
        Query<Message> query = session.createQuery(hql, Message.class);
        return query.list();
    }


}
